<template>
  <div id="grantPayslip">
    <div class="content">
      <el-card class="peopleList">
        <div class="title" slot="header">
          发放人员列表
          <el-checkbox class="checkAll" :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        </div>
        <!-- 发放人员列表  -->
        <el-checkbox-group v-model="checkUser" @change="handleCheckedUserChange">
          <el-checkbox class="checkItem" v-for="user in dataForm.userList" :label="user" :key="user.userId">{{user.userName}}</el-checkbox>
        </el-checkbox-group>
      </el-card>
      <div class="preview">
        <!-- <p>预览</p>  -->
        <div class="previewContent">
          <div class="hiddenBox">
            <div class="previewInfo">
              <p class="title">{{$route.query.month}}月工资</p>
              <p class="total">
                <span>实发工资</span>
                <!-- <span>5000.00</span> -->
              </p>
              <!-- 中间 -->
              <div class="infoForm" v-for="(item,itemIndex) in itemList" v-show="isShowPreviewCard(item)" :key="itemIndex">
                <p class="infoTitle">{{item.itemName}}</p>
                <template v-for="col in item.columnList">
                  <div class="listItem" v-show="checkedColumnList.findIndex(e => e.columnName == col.columnName) != -1" :key="col.physicalSort">
                    <span>{{col.columnName}}</span>
                  </div>
                </template>
              </div>
            </div>
          </div>

        </div>
      </div>
      <!-- 薪资信息 -->
      <div class="infoList">
        <el-card class="staffInfo" v-for="(item,index) in itemList" :key="item.itemName">
          <div class="title" slot="header">{{item.itemName}}</div>
          <el-checkbox-group v-model="checkedColumnList" @change="handleChangeConsole">
            <div class="listItem" v-for="(col,colIndex) in item.columnList" :key="col.physicalSort">
              <el-checkbox class="checkItem" :label="col" :disabled="['姓名','工号','实发工资'].includes(col.columnName)">
                {{col.columnName}}
              </el-checkbox>
              <div class="btnList">
                <i class="el-icon-top" v-show="colIndex != 0" @click.stop="handleChangeOrder('up',index,colIndex)" />
                <i class="el-icon-bottom" v-show="colIndex <item.columnList.length -1 " @click.stop="handleChangeOrder('down',index,colIndex)" />
              </div>
            </div>
          </el-checkbox-group>
        </el-card>
      </div>
    </div>
    <div class="footer">
      <el-button @click="handleCancel"> 取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认发放</el-button>
    </div>
  </div>
</template>
<script>
import eventBus from "@/views/personnelRegulate/rewardManagement/smartSalary/salarySheet/eventBus/eventBus";
export default {
  name: 'grantPayslip',
  data() {
    return {
      // staffInfo
      checkAll: false,
      checkUser: [],
      isIndeterminate: true,
      dataForm: {
        // 用户列表
        userList: [],
        // 大循环表
        itemList: [],
        // 小循环表
        columnList: [],
      },
      itemList: [],
      checkedColumnList: [],
      checkedItemList: [],
      useIdList: [],
      arrList: []
    };
  },
  methods: {
    searchDataList(wagesId, tempId) {
      if(this.$route.query.sourceType === undefined) {
        this.$route.query.sourceType = 1;
        this.useIdList = [];
      }else if(this.$route.query.sourceType === 2) {
        this.$route.query.sourceType = 2;
      }else {
        this.$route.query.sourceType = 1;
      }
      if(this.$route.query.sourceType === 1) {
        this.$route.query.confirmWay = 0;
      }
      let params = {
        tempId,
        wagesId,
        sourceType: this.$route.query.sourceType,
        userIdList: this.useIdList,
        payslipId: this.$route.query.payslipId,
        confirmWay: this.$route.query.confirmWay
      };
      this.$api.electronicPayslip
        // `?tempId=${tempId}&wagesId=${wagesId}`
        .GetPaySlipTempList(params)
        .then(res => {
          if (res.data.status == 200) {
            this.dataForm = res.data.data;
            this.itemList = this.formatListData(res.data.data.itemList, res.data.data.columnList);
            if(this.$route.query.pageName === "continue") {
              var getItem = JSON.parse(sessionStorage.getItem('arrList'));
              getItem.getArrlist.map((v)=>{
                this.dataForm.userList.map((e)=>{
                  if(v == e.userName) {
                    e.isIssued = true;
                    this.checkUser.push(e);
                  }
                });
              });
            } else {
              // 循环用户所有项  找到勾选字段
              this.dataForm.userList.map((v)=>{
                if(v.isIssued === true) {
                  this.checkUser.push(v);
                }
              });
            }
            // 循环右侧个人信息和薪资所有项 找到勾选字段
            this.dataForm.columnList.map((e)=>{
              if(e.isSelectColumn === true) {
                this.checkedColumnList.push(e);
              }
            });
            // if (this.$route.query.page && this.$route.query.page == 'electronicPayslipDetails') {
            //   // 从vuex中获取要发送工资条的员工列表及其他信息
            //   this.checkUser = [];
            //   this.$store.state.reward.grantPayslipRouteData.userList.map(e => {
            //     const index = this.dataForm.userList.findIndex(user => user.userId == e.userId);
            //     if (index != -1) {
            //       this.checkUser.push(this.dataForm.userList[index]);
            //     }
            //   });
            //   this.checkedColumnList = [];
            // }
          }
        });
    },
    searchHistory(payslipId, userIdList) {

      this.$api.electronicPayslip
        .GetIssueUserDetail({
          payslipId,
          userIdList,
          operateType: userIdList.length > 1 ? 2 : 1
        })
        .then(res => {
          if (res.data.data) {
            console.log(res.data.data, '根据查询到的历史设置默认勾选项');
            let itemList = [];
            this.itemList.map(e => {
              itemList = [...itemList, ...e.columnList];
            });
            res.data.data.map(e => {
              const index = itemList.findIndex(item => item.id == e.salaryColumnId);
              index != -1 ? this.checkedColumnList.push(itemList[index]) : '';
            });

          }
        });
    },
    formatListData(itemList, columnList) {
      console.log("列表数据格式化");
      // 创建薪资信息类型
      let salaryItem = {
        itemName: '薪资信息',
        id: itemList[0].id, // 为薪资信息也附上个人信息的id，在控制大类显示时根据itemName进行区分
        columnList: [],
      };
      itemList = itemList.map(e => {
        e.columnList = [];
        columnList.map(col => {
          if (col.salaryItemId == e.id) {
            e.columnList.push(col);
          } else {
            // 将类型不为个人信息的数据放在薪资信息里
            salaryItem.columnList.push(col);
          }

          if (['姓名', '工号', '实发工资'].includes(col.columnName)) {
            this.checkedColumnList.push(col);
          }
        });
        return e;
      });
      itemList.push(salaryItem);
      return itemList;
    },
    isShowPreviewCard(item) {
      const index = item.itemName == '个人信息' ? this.checkedColumnList.findIndex(e => item.id == e.salaryItemId) : this.checkedColumnList.findIndex(e => item.id != e.salaryItemId);
      return index != -1;
    },
    addPayslip(data) {
      this.$api.electronicPayslip
        .AddPayslip(data)
        .then(res => {
          console.log(res);
          if (res.data.status == 200) {
            this.$message.success(res.data.message);
            this.goBackToList();
          }
        });
    },
    goBackToList() {

      this.$store.commit('DEL_TAG', {
        value: this.$route.path,
        label: this.$route.meta.title
      });
      if (this.$route.query.page && this.$route.query.page == 'electronicPayslipDetails') {
        this.$router.replace({
          path: '/electronicPayslipDetails'
        });
      } else {
        this.$router.replace({
          path: '/electronicPayslip'
        });
      }

    },
    handleChangeConsole(data) {
      console.log('勾选修改', data);
    },
    handleCheckAllChange(val) {
      this.checkUser = val ? this.dataForm.userList : [];
      this.isIndeterminate = false;
    },
    handleCheckedUserChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.dataForm.userList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.dataForm.userList.length;
    },

    /**
     * @description 切换点击项顺序
     * @param orderType 向上还是向下移动 up | down
     * @param index 在当前列表中下标
     * @param listName 当前列表的属性名
     */
    handleChangeOrder(orderType, index, colIndex) {
      if (orderType == 'up') {
        const data = this.itemList[index].columnList[colIndex - 1];
        this.itemList[index].columnList.splice(colIndex - 1, 1, this.itemList[index].columnList[colIndex]);
        this.itemList[index].columnList.splice(colIndex, 1, data);
      } else {
        const data = this.itemList[index].columnList[colIndex + 1];
        console.log(data);
        this.itemList[index].columnList.splice(colIndex + 1, 1, this.itemList[index].columnList[colIndex]);
        this.itemList[index].columnList.splice(colIndex, 1, data);
      }
      this.$forceUpdate();
    },
    handleCancel() {
      this.$router.go(-1);       
      // this.goBackToList();
      // this.$store.commit('DEL_TAG', {
      //   value: this.$route.path,
      //   label: this.$route.meta.title
      // });
      // this.$router.replace({
      //   path: '/electronicPayslip'
      // });
    },
    handleSubmit() {
      if (this.checkedColumnList.length == 0 || this.checkUser.length == 0) {
        const tip = this.checkedColumnList.length == 0 ? '请勾选工资条条目' : '请勾选需要发放的人员';
        return this.$message.warning(tip);
      }
      const payslipId = parseInt(this.$route.query.payslipId);
      const wagesId = parseInt(this.$route.query.wagesId);
      const monthNumber = parseInt(this.$route.query.month);
      const yearNumber = parseInt(this.$route.query.year);
      // 对勾选项数据进行格式化
      let requestData = {
        payslipId,
        wagesId,
        yearNumber,
        monthNumber,
        payslipHeadList: [],
        issueUserList: []
      };

      this.itemList.map(item => {
        item.columnList.map(col => {
          if (this.checkedColumnList.findIndex(icol => col.physicalSort == icol.physicalSort) != -1) {
            requestData.payslipHeadList.push({
              id: 0,
              payslipId,
              wagesHeadId: col.wagesHeadId,
              salaryItemId: col.salaryItemId,
              salaryItemName: item.itemName,
              salaryColumnId: col.id,
              salaryColumnName: col.columnName,
              // columnValue: item.itemName == '薪资信息' ? '0' : 'xxx', 已弃用 不显示详细数据
              columnValue: '',
              itemSort: 0,
              columnSort: requestData.payslipHeadList.length + 1,
              subId: col.subId,
              companyId: col.companyId,
              isCustom: col.isCustom,
              columnNamePy: col.columnNamePy,
            });
          }
        });
      });
      requestData.issueUserList = [];
      requestData.issueUserList = this.checkUser.map(e => {
        return {
          id: 0,
          payslipId,
          userId: e.userId,
          userName: e.userName,
          subId: e.subId,
          companyId: e.companyId,
          createTime: '',

        };
      });
      this.addPayslip(requestData);
    }
  },

  activated() {
    var getuseIdList = JSON.parse(sessionStorage.getItem('useIdList'));
    if(this.$route.query.page && this.$route.query.page == 'electronicPayslipDetails') {
      this.useIdList = getuseIdList.userLists;
      this.checkUser = [];
      this.checkedColumnList = [];
    }else {
      this.useIdList = [];
      this.checkedColumnList = [];
    }
    this.searchDataList(this.$route.query.wagesId, this.$route.query.tempId);
    // if (this.$route.query.page && this.$route.query.page == 'electronicPayslipDetails') {
    // 从vuex中获取要发送工资条的员工列表及其他信息
    // console.log('this.$store.state.reward.grantPayslipRouteData', this.$store.state.reward.grantPayslipRouteData);
    // this.$store.state.reward.grantPayslipRouteData.userList.map(e => {
    //   this.checkUser.push(e);
    // });
    // console.log(this.checkUser);
    // }
  },
  destroyed() {
    eventBus.$off();
  },
};
</script>
<style lang="less" scoped>
@import url(./less/grantPayslip.less);
</style>
